package com.piepesken.mediscale.di

import android.content.Context
import androidx.room.Room
import com.huaweicloud.sdk.core.auth.BasicCredentials
import com.huaweicloud.sdk.core.http.HttpConfig
import com.huaweicloud.sdk.iotda.v5.IoTDAClient
import com.huaweicloud.sdk.iotda.v5.region.IoTDARegion
import com.piepesken.mediscale.BuildConfig
import com.piepesken.mediscale.data.RoomDataSource
import com.piepesken.mediscale.models.DrugDao
import com.piepesken.mediscale.utils.DATABASE_NAME
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

/**
 * TODO: Split logic.
 */
@Module
@InstallIn(SingletonComponent::class)
class DataSourceModule {
    @Singleton
    @Provides
    fun provideHuaweiIotdaApi(@ApplicationContext context: Context): IoTDAClient {
        // Set up authentication
        val auth = BasicCredentials()
            .withAk(BuildConfig.HUAWEI_API_AK)
            .withSk(BuildConfig.HUAWEI_API_SK)
            .withProjectId(BuildConfig.HUAWEI_API_PROJECT_ID)

        // Create IotdaClient instance
        return IoTDAClient.newBuilder()
            .withHttpConfig(HttpConfig.getDefaultHttpConfig())
            .withCredential(auth)
            .withRegion(IoTDARegion.CN_NORTH_4)
            .withEndpoint(BuildConfig.HUAWEI_API_ENDPOINT)
            .build()
    }

    @Singleton
    @Provides
    fun provideRoomDataSource(@ApplicationContext context: Context): RoomDataSource {
        return Room.databaseBuilder(context, RoomDataSource::class.java, DATABASE_NAME)
            .createFromAsset("database.db")
            .fallbackToDestructiveMigration()
            .build()
    }

    @Singleton
    @Provides
    fun drugDao(db: RoomDataSource): DrugDao = db.drugDao()
}
